package com.baihui.taobao.transition;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.MemberDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BCrmMember;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.BasicMember;
import com.taobao.api.request.CrmMembersGetRequest;
import com.taobao.api.request.CrmMembersSearchRequest;
import com.taobao.api.response.CrmMembersGetResponse;
import com.taobao.api.response.CrmMembersSearchResponse;

import java.sql.Connection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-2-11 Time: 上午7:38
 */
public class MemberCase extends Cases implements IViewProgressSupport {
	public MemberCase(TaoBaoSessionInfo info) {
		super(info);
	}

	public List<BasicMember> getMemberInfo(Date startDate, Date endDate)
			throws Exception {
		CrmMembersGetRequest req = new CrmMembersGetRequest();
		long page = 1;
		req.setCurrentPage(page);
		req.setPageSize(99l);
		req.setMinLastTradeTime(startDate);
		req.setMaxLastTradeTime(endDate);
		try {
			CrmMembersGetResponse response = getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
			if (response.getErrorCode() != null) {
				throw new Exception();
			}
			List<BasicMember> memberList = response.getMembers();
			if (memberList == null || memberList.size() <= 0)
				return null;
			while (response != null
					&& response.getTotalResult() > memberList.size()) {
				// 存在第二页
				Util.stopOneMinute();
				page++;
				response = getNextPage(req, page);
				if (response.getErrorCode() == null) {
					memberList.addAll(response.getMembers());
				} else {
					response = getNextPage(req, page);
					memberList.addAll(response.getMembers());
				}
			}
			return memberList;
		} catch (Exception e) {
			throw e;
		}
	}

	private CrmMembersGetResponse getNextPage(CrmMembersGetRequest req,
			long page) throws Exception {
		req.setCurrentPage(page);
		try {
			return getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	private SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	public void importMemberFromTaobao(long visitor_id, Date start, Date end)
			throws Exception {
		if (start == null || end == null) {
			end = new Date();
			start = addMonths(end, -3);
		}
		List<BasicMember> memberList = getMemberInfo(start, end);
		List<String> memList = getMemberByUser();
		Connection cn = null;
		try {
			if (memberList != null && memberList.size() > 0) {
				List<TaobaoObject> allMemberInfos = new ArrayList<TaobaoObject>();
				for (BasicMember member : memberList) {
					if (memList != null
							&& memList.contains(String.valueOf(member.getBuyerId()))) {
						continue;
					}
					BCrmMember tmp = new BCrmMember();
					Util.copy(tmp, member);
					tmp.setUserId(visitor_id);
					allMemberInfos.add(tmp);
					// }
				}
				cn = DBConnectionMgr.getConnection();
				// log("更新店铺会员信息表！");
				MemberDAO memberDAO = new MemberDAO();
				memberDAO.insert(allMemberInfos, cn);
				allMemberInfos.clear();
			}
		} catch (Exception e) {
			// if (cn != null) cn.rollback();
			throw e;
		} finally {
			if (cn != null)
				cn.close();
		}

	}

	/**
	 * 找出重复的记录，并且根据lastTradeTime来取得最大值
	 * 
	 * @param allMemberInfos
	 * @param member
	 * @return
	 */
	private boolean canAdd(List<TaobaoObject> allMemberInfos, BasicMember member) {
		if (allMemberInfos == null || allMemberInfos.size() <= 0)
			return true;
		java.util.Iterator iter = allMemberInfos.iterator();
		while (iter.hasNext()) {
			BCrmMember crmMember = (BCrmMember) iter.next();
			if (crmMember.getBuyerId().equals(member.getBuyerId())) {
				if (crmMember.getLastTradeTime() != null
						&& member.getLastTradeTime() != null) {
					if (crmMember.getLastTradeTime().getTime() >= member
							.getLastTradeTime().getTime()) {
						return false;
					} else {
						iter.remove();
						return true;
					}
				} else {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 得到最大的结束日期
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 */
	public Timestamp getMaxEndTime(Timestamp startDate, Timestamp endDate)
			throws Exception {
		CrmMembersSearchRequest req = new CrmMembersSearchRequest();
		long page = 1;
		req.setCurrentPage(page);
		req.setPageSize(99l);
		req.setMinLastTradeTime(startDate);
		req.setMaxLastTradeTime(endDate);
		try {
			CrmMembersSearchResponse response = getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
			if (response.getTotalResult() > getSessionInfo().getTbMaxCount()) {
				long times = response.getTotalResult()
						/ getSessionInfo().getTbMaxCount();
				long period = endDate.getTime() - startDate.getTime();
				if (times >= 1) {
					endDate = new Timestamp(startDate.getTime() + period
							/ times);
				}
			}
			return endDate;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		getSessionInfo().setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return getSessionInfo().getOrderImportProgress();
	}

	/**
	 * 本用户对应的物流信息
	 * 
	 * @return
	 */
	public List<String> getMemberByUser() throws Exception {
		CommonDAO commonDAO = new CommonDAO();
		List<String> memberMap = commonDAO.findListString(
				"select buyerId from tbcrmmember where userId = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		return memberMap;
	}
}
